//
//  ECSScriptApi_view.m
//  ECS DevelopKit
//
//  Created by LittoCats on 8/26/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "ECSScriptApi_view.h"
#import "ECSViewController.h"

#import "ECSScriptApi_page.h"

#import "NSObject+ECS.h"
#import "ECSUIDelegate.h"
#import "ECSUIBuilder.h"

@implementation ECSScriptApi_view

+ (void)analyseAction:(NSMutableDictionary *)action
{
    [(id<ECSScriptApiProtocol>)ECSScriptApi_page.class analyseAction:action];
    
    //解析 view
    UIView *view;
    NSString *view_id = [action objectForKey:@"view"];
    if ((!view_id || [view_id isEmpty]) && [action objectForKey:@"page"])
        view = [[action objectForKey:@"page"] view];
    else if (view_id && ![view_id isEmpty]){
        view = [NSObject findObjectById:view_id];
        if (!view)
            view_id = [[action objectForKey:ECSScriptContextKey] evaluateScript:[[NSString alloc] initWithFormat:@"if (typeof %@ !== 'undefined')  %@; else console.log('this context doesn't hold view with id < %@ > .');",view_id,view_id,view_id]];
        if (view_id && ![view_id isEmpty])
            view = [NSObject findObjectById:view_id];
    }
    NSAssert(view, @"[ECSScriptApi_view] error : can't find view with action info < %@ >",action);
    [action setObject:view forKey:@"view"];
}

#pragma mark- 属性及数据
+ (void)ECS_Script_API(attr)
{
    NSMutableDictionary *result = [NSMutableDictionary new];
    for (id attr in arguments){
        id value = [ECSUIAttributesParser parseAttributes:attr forView:action[@"view"]];
        if ([attr isKindOfClass:NSString.class])
            [result setObject:value ? value : NSNull.null forKey:attr];
    }
    handler(result);
}


+ (void)ECS_Script_API(refresh)
{
    if ([action[@"view"] respondsToSelector:@selector(refresh:)])
        [(id<ECSScriptApi_view>)action[@"view"] refresh:arguments.count ? arguments[0] : nil];
}


#pragma mark- 用户事件
+ (void)ECS_Script_API(onClick)
{
    id callback = arguments.count ? arguments[0] : nil;
    if ([action[@"view"] respondsToSelector:@selector(onClick:)])
        [(id<ECSScriptApi_view>)(action[@"view"]) onClick:callback];
    else
        [ECSUIDelegate addOnClickEvent:callback forResponder:action[@"view"]];
    
}

+ (void)ECS_Script_API(onItemClick)
{
    id callback = arguments.count ? arguments[0] : nil;
    if ([action[@"view"] respondsToSelector:@selector(onItemClick:)])
        [(id<ECSScriptApi_view>)(action[@"view"]) onItemClick:callback];
}
@end
